package com.exm.collectcodenew.activemq.consumer;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class ActiveMQTopicConsumer {
    public static final String ACTIVEMQ_URL ="tcp://59.110.35.177:61616";
    public static final String TOPIC_NAME="topic01";

    public static void main(String[] args) throws JMSException {
        //1.连接工厂，按照给定的url地址，采用默认用户名和密码
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工厂，获取连接connection并启动访问
        Connection connection =activeMQConnectionFactory.createConnection();
        connection.start();
        //3.创建会话session
        //两个参数，第一个叫事务/第二个叫签收
        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        //4.创建目的地（具体是队列还是主题topic）
        Topic topic =session.createTopic(TOPIC_NAME);
        //5.创建消息的消费者
        MessageConsumer messageConsumer=session.createConsumer(topic);
        while (true){
            Message message=  messageConsumer.receive();
            if(message!=null && message instanceof TextMessage){
                TextMessage textmessage = (TextMessage)message;
                System.out.println("接受的消息为："+textmessage.getText());
            }else {
                break;
            }
        }

        //7.关闭资源
        messageConsumer.close();
        session.close();
        connection.close();
        System.out.println("****消息消费完成****");
    }
}
